package com.wchen.project.zk.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * @Desc:   使用同步 API 获取节点数据内容
 *          注意：数据内容或者数据版本变化，都会触发服务端的 NodeDataChanged 通知
 * @author: cww
 * @DateTime: 2020-01-18 10:24
 */

public class ZooKeeperGetDataSyncAPI implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zk = null;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws Exception{
        String path = "/zk-book";
        zk  = new ZooKeeper("home:2181", 5000, new ZooKeeperGetDataSyncAPI());
        connectedSemaphore.await();
//        zk.delete(path, -1);
        zk.create(path, "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println(new String(zk.getData(path, true, stat)));
        System.out.println("Czxid：" + stat.getCzxid() + ", Mzxid: " + stat.getMzxid() + ", Version: " + stat.getVersion());
        zk.setData(path, "456".getBytes(), -1);
        Thread.sleep(50000);
    }
    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                connectedSemaphore.countDown();
            } else if (event.getType() == Event.EventType.NodeDataChanged) {
                try {
                    System.out.println(new String(zk.getData(event.getPath(), true, stat)));
                    System.out.println("Czxid：" + stat.getCzxid() + ", Mzxid: " + stat.getMzxid()
                            + ", Version: " + stat.getVersion());
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

